package io.github.noahzu.daka

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.ActionBar
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import cn.leancloud.AVObject
import cn.leancloud.AVQuery
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import io.github.noahzu.daka.adapter.DataAdapter
import io.github.noahzu.daka.bean.ConstructionBean
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*


class MainActivity : BaseActivity() {
    companion object {
        const val REQUEST_ADD_CODE = 0x100
    }
    private val mAdapter: DataAdapter = DataAdapter(this)

    override fun layoutId(): Int = R.layout.activity_main
    override fun beforeCreate() {
        val actionBar: ActionBar? = supportActionBar
        actionBar?.hide()
    }

    override fun afterCreate() {
        mDataListView.adapter = mAdapter
        mDataListView.layoutManager = LinearLayoutManager(this)
        mDataListView.addItemDecoration(DividerItemDecoration(this,DividerItemDecoration.VERTICAL))
        doRequestPermission()
        mRefreshLayout.setOnRefreshListener {
            doRefresh()
        }
        mRefreshLayout.autoRefresh()
        doAddClikck()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == REQUEST_ADD_CODE && resultCode == Activity.RESULT_OK) {
            mRefreshLayout.autoRefresh()
        }
    }

    private fun doAddClikck() {
        mAddProjectBtn.setOnClickListener {
            startActivityForResult(Intent(this,AddProjectActivity::class.java),REQUEST_ADD_CODE)
        }
    }

    private fun doRefresh() {
        val query = AVQuery<AVObject>("ConstructionBean")
        query.addDescendingOrder("createdAt")
        query.findInBackground()
            .subscribeOn(Schedulers.io())//这里指定在io线程执行
            .observeOn(AndroidSchedulers.mainThread())//返回结果在主线程执行
            .subscribe(object : Observer<List<AVObject>> {
                override fun onSubscribe(disposable: Disposable) {

                }
                override fun onError(throwable: Throwable) {
                    ToastUtils.showShort("获取数据错误")
                    mRefreshLayout.finishRefresh()
                }
                override fun onComplete() {
                    mRefreshLayout.finishRefresh()
                }
                override fun onNext(t: List<AVObject>) {
                    val beans = ArrayList<ConstructionBean>()
                    t.forEach {
                        beans.add(ConstructionBean(
                            it.getString("ConstructionUnit"),
                            it.getString("Notes"),
                            it.getString("ProjectName"),
                            it.getString("Projectlocation"),
                            it.getString("Remarks")?:"",
                            it.getString("Sponsor"),
                            it.getDate("Time"),
                            it.getString("VerbalWarning")?:"",
                            it.getString("personInCharge")
                        ))
                    }
                    mAdapter.mData.clear()
                    mAdapter.mData.addAll(beans)
                    mAdapter.notifyDataSetChanged()
                    mRefreshLayout.finishRefresh()
                }
            })
    }

    private fun doRequestPermission() {
        PermissionUtils.permission(PermissionConstants.STORAGE)
            .callback(object : PermissionUtils.FullCallback {
                override fun onGranted(permissionsGranted: List<String>) {
                    LogUtils.d(permissionsGranted)

                }

                override fun onDenied(
                    permissionsDeniedForever: List<String>,
                    permissionsDenied: List<String>
                ) {
                    LogUtils.d(permissionsDeniedForever, permissionsDenied)
                }
            })
            .request()
    }

}
